package sqlite_conf_table

import (
	"database/sql"
	"github.com/sirupsen/logrus"
	"go-iot-gateway/internal/conf_table/define"
	"strings"
)

//规则属性

/*
id
chl_id
f_name
f_pno
f_no
f_desc
f_dataflag
f_value
*/

var tbProtocolSetAttrColumns = []string{
	"id",
	"chl_id",
	"f_name",
	"f_pno",
	"f_no",
	"f_desc",
	"f_dataflag",
	"f_value",
}

type tbProtocolSetAttrEntity struct {
	id         *int
	chl_id     *string
	f_name     *string
	f_pno      *string
	f_no       *int
	f_desc     *string
	f_dataflag *int
	f_value    *string
}

var (
	_tbProtocolSetAttr map[string][]*conf_table_define.ProtocolInfo //key chl_id
)

func ProtocolConfInfoList(chl_id string) []*conf_table_define.ProtocolInfo {
	return _tbProtocolSetAttr[chl_id]
}

func selectProtocolConfInfo(db *sql.DB) error {
	//查询 protocol attr
	fields := strings.Join(tbProtocolSetAttrColumns, ",")
	select_sql := "select " + fields + " from tb_protocol_setattr order by chl_id"
	rows, err := db.Query(select_sql)
	if err != nil {
		return err
	}
	defer func() {
		err := rows.Close()
		if err != nil {
			logrus.Warn("行关闭失败")
			return
		}
	}()

	_tbProtocolSetAttr, err = convertProtocolConfInfo(rows)
	if err != nil {
		return err
	}
	return nil
}

func convertProtocolConfInfo(rows *sql.Rows) (map[string][]*conf_table_define.ProtocolInfo, error) {

	err := rows.Err()
	if err != nil {
		return nil, err
	}

	resultMap := make(map[string][]*conf_table_define.ProtocolInfo)
	for rows.Next() {
		entity := tbProtocolSetAttrEntity{}
		err := rows.Scan(
			&entity.id,
			&entity.chl_id,
			&entity.f_name,
			&entity.f_pno,
			&entity.f_no,
			&entity.f_desc,
			&entity.f_dataflag,
			&entity.f_value)

		if err != nil {
			return nil, err
		}

		item := &conf_table_define.ProtocolInfo{}

		if entity.id != nil {
			item.Id = *entity.id
		}
		if entity.chl_id != nil {
			item.Chl_id = *entity.chl_id
		}
		if entity.f_name != nil {
			item.F_name = *entity.f_name
		}
		if entity.f_pno != nil {
			item.F_pno = *entity.f_pno
		}
		if entity.f_no != nil {
			item.F_no = *entity.f_no
		}
		if entity.f_desc != nil {
			item.F_desc = *entity.f_desc
		}
		if entity.f_dataflag != nil {
			item.F_dataflag = *entity.f_dataflag
		}
		if entity.f_value != nil {
			item.F_value = *entity.f_value
		}

		if infos, ok := resultMap[item.Chl_id]; ok {
			resultMap[item.Chl_id] = append(infos, item)
		} else {
			infos := make([]*conf_table_define.ProtocolInfo, 0, 15)
			infos = append(infos, item)
			resultMap[item.Chl_id] = infos
		}
	}

	return resultMap, nil

}
